package leetcode.trie.p677;

import java.util.TreeMap;

/**
 * 
 * @Title: MapSum.java 
 * @Package leetcode.trie.p677 
 * @Description: 677. 键值映射
 * @author CandyWall   
 * @date 2021年1月10日 下午9:23:05 
 * @version V1.0
 */
class MapSum {
    private class Node {
        public int val;
        TreeMap<Character, Node> next;

        public Node() {
            this.next = new TreeMap<>();
        }
    }

    private Node root;

    /** Initialize your data structure here. */
    public MapSum() {
        root = new Node();
    }
    
    public void insert(String key, int val) {
        Node cur = root;
        for(int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if(!cur.next.containsKey(c)) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        cur.val = val;
    }
    
    public int sum(String prefix) {
        Node cur = root;
        for(int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(!cur.next.containsKey(c)) {
                return 0;
            }
            cur = cur.next.get(c);
        }
        
        return sum(cur);
    }
    
    private int sum(Node node) {
        int res = node.val;
        
        for(Character c : node.next.keySet()) {
            res += sum(node.next.get(c));
        }
        
        return res;
    }
    
    public static void main(String[] args) {
        MapSum mapSum = new MapSum();
        mapSum.insert("apple", 3);  
        System.out.println(mapSum.sum("ap"));           // return 3 (apple = 3)
        mapSum.insert("app", 2);
        System.out.println(mapSum.sum("ap"));           // return 5 (apple + app = 3 + 2 = 5)
    }
}